#! /usr/bin/env python
# pymanyou - Python bindings for the Manyou API
# Copyright (c) 2008, (Damien) Yongrong Hou houyongr(at)gmail dot com
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This work is based on pyfacebook, whose license is shown below
#
# Copyright (c) 2008, Samuel Cormier-Iijima
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the <organization> nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY <copyright holder> ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""
Python bindings for the Manyou API (pymanyou - http://code.google.com/p/pymanyou)

pymanyou is a client library that wraps the Manyou API.

For more information, see

Home Page: http://code.google.com/p/pymanyou
Developer Wiki: http://code.google.com/p/pymanyou/w/list

Response format defaults to JSON
"""

import base64
import logging
import md5
import sys
import time
import urllib
import urllib2
import httplib
import urlparse
import mimetypes
from urlparse import urljoin

# try to use simplejson first, otherwise fallback to XML
try:
    import simplejson
    RESPONSE_FORMAT = 'JSON'
except ImportError:
    try:
        from django.utils import simplejson
        RESPONSE_FORMAT = 'JSON'
    except ImportError:
        from xml.dom import minidom
        RESPONSE_FORMAT = 'PHP'
# support Google App Engine.  GAE does not have a working urllib.urlopen.
try:
    from google.appengine.api import urlfetch

    def urlread(url, data=None):
        if data is not None:
            headers = {"Content-type": "application/x-www-form-urlencoded"}
            method = urlfetch.POST
        else:
            headers = {}
            method = urlfetch.GET

        result = urlfetch.fetch(url, method=method,
                                payload=data, headers=headers)
        
        if result.status_code == 200:
            return result.content
        else:
            raise urllib2.URLError("fetch error url=%s, code=%d" % (url, result.status_code))

except ImportError:
    def urlread(url, data=None):
        res = urllib2.urlopen(url, data=data)
        return res.read()
    
__all__ = ['Manyou']

VERSION = '1.0'

# REST URLs
MANYOU_URL = 'http://api.manyou.com/openapi.php'
MANYOU_SECURE_URL = 'https://api.manyou.com/openapi.php'

class json(object): pass

# simple IDL for the Manyou API
METHODS = {
    # feed methods
    'feed': {
        'publishTemplatizedAction': [
            ('title_template', str, []),
            ('title_data', json, ['optional']),
            ('body_template', str, ['optional']),
            ('body_data', json, ['optional']),
            ('body_general', str, ['optional']),
            ('image_1', str, ['optional']),
            ('image_1_link', str, ['optional']),
            ('image_2', str, ['optional']),
            ('image_2_link', str, ['optional']),
            ('image_3', str, ['optional']),
            ('image_3_link', str, ['optional']),
            ('image_4', str, ['optional']),
            ('image_4_link', str, ['optional']),
        ],
    },

    # friends methods
    'friend': {
        'areFriends': [
            ('uid1', list, []),
            ('uid2', list, []),
        ],

        'getFriends': [],

        'getAppUsers': [],
        
        'get': [],
    },

    # notifications methods
    'notification': {
        'get': [],

        'send': [
            ('uids', list, []),
            ('msg', str, []),
        ],
    },

    # profile methods
    'profile': {
        'setMYML': [
            ('myml', str, []),
            ('uid', int, ['optional']),
        ],

        'getMYML': [
            ('uid', int, ['optional']),
        ],
    },

    # users methods
    'user': {
        'getInfo': [
            ('uids', list, []),
            ('fields', list, [('default', ['name'])]),
        ],

        'getLoggedInUser': [],

        'isAppAdded': [
            ('uid', int, ['optional']),
        ],
    },
    
    # fql methods
    'myql': {
        'query': [
            ('query', str, []),
        ],
    },
}

class Proxy(object):
    """Represents a "namespace" of Manyou API calls."""

    def __init__(self, client, name):
        self._client = client
        self._name = name

    def __call__(self, method, args=None, add_session_args=True):
        if add_session_args:
            self._client._add_session_args(args)

        return self._client('%s.%s' % (self._name, method), args)


# generate the Manyou proxies
def __generate_proxies():
    for namespace in METHODS:
        methods = {}

        for method in METHODS[namespace]:
            params = ['self']
            body = ['args = {}']

            for param_name, param_type, param_options in METHODS[namespace][method]:
                param = param_name

                for option in param_options:
                    if isinstance(option, tuple) and option[0] == 'default':
                        if param_type == list:
                            param = '%s=None' % param_name
                            body.append('if %s is None: %s = %s' % (param_name, param_name, repr(option[1])))
                        else:
                            param = '%s=%s' % (param_name, repr(option[1]))

                if param_type == json:
                    # we only jsonify the argument if it's a list or a dict, for compatibility
                    body.append('if isinstance(%s, list) or isinstance(%s, dict): %s = simplejson.dumps(%s)' % ((param_name,) * 4))

                if 'optional' in param_options:
                    param = '%s=None' % param_name
                    body.append('if %s is not None: args[\'%s\'] = %s' % (param_name, param_name, param_name))
                else:
                    body.append('args[\'%s\'] = %s' % (param_name, param_name))

                params.append(param)

            # simple docstring to refer them to Manyou API docs
            body.insert(0, '"""Manyou API call. See http://dev.manyou.com/wiki/%s.%s"""' % (namespace, method))

            body.insert(0, 'def %s(%s):' % (method, ', '.join(params)))

            body.append('return self(\'%s\', args)' % method)

            exec('\n    '.join(body))

            methods[method] = eval(method)

        proxy = type('%sProxy' % namespace.title(), (Proxy, ), methods)

        globals()[proxy.__name__] = proxy


__generate_proxies()


class ManyouError(Exception):
    """Exception class for errors received from Manyou."""

    def __init__(self, code, msg, args=None):
        self.code = code
        self.msg = msg
        self.args = args

    def __str__(self):
        return 'Error %s: %s' % (self.code, self.msg)


class AuthProxy(Proxy):
    """Special proxy for manyou.auth."""

    def getSession(self):
        """Manyou API call. See http://dev.manyou.com/wiki/auth.getSession"""
        args = {}
        try:
            args['auth_token'] = self._client.auth_token
        except AttributeError:
            raise RuntimeError('Client does not have auth_token set.')
        result = self._client('%s.getSession' % self._name, args)
        self._client.session_key = result['session_key']
        self._client.uid = result['uid']
        self._client.secret = result.get('secret')
        self._client.session_key_expires = result['expires']
        return result

    def createToken(self):
        """Manyou API call. See http://dev.manyou.com/wiki/auth.createToken"""
        token = self._client('%s.createToken' % self._name)
        self._client.auth_token = token
        return token


class FriendProxy(FriendProxy):
    """Special proxy for manyou.friends."""

    def get(self, **kwargs):
        """Manyou API call. See http://wiki.developer.manyou.com/wiki/index.php/Friend.get"""
        if self._client._friends:
            return self._client._friends
        return super(FriendProxy, self).get(**kwargs)

class Manyou(object):
    """
    Provides access to the Manyou API.

    Instance Variables:

    added
        True if the user has added this application.

    api_key
        Your API key, as set in the constructor.

    app_id
        Your application's id on Manyou, i.e. the APP_ID in http://uchome.developer.manyou.com/uchome/userapp.php?id=APP_ID if
        this is for an internal web application. Optional, but useful for automatic redirects
        to canvas pages.
        
    prefix
        The URL prefix of a Manyou enabled UChome website. Optional, used to automatically construct the app canvas page

    auth_token
        The auth token that Manyou gives you, either with manyou.auth.createToken,
        or through a GET parameter.

    callback_path
        The path of the callback set in the Manyou app settings. If your callback is set
        to http://www.example.com/manyou/callback/, this should be '/manyou/callback/'.
        Optional, but useful for automatic redirects back to the same page after login.

    internal
        True if this Manyou object is for an internal application (one that can be added on Manyou)

    secret
        Secret that is used after getSession for desktop apps.

    secret_key
        Your application's secret key, as set in the constructor.

    session_key
        The current session key. Set automatically by auth.getSession, but can be set
        manually for doing infinite sessions.

    session_key_expires
        The UNIX time of when this session key expires, or 0 if it never expires.

    uid
        After a session is created, you can get the user's UID with this variable. Set
        automatically by auth.getSession.
    
    sid
        Unique UCHome instance site id. Used to determine which site the current user
        belongs to

    ----------------------------------------------------------------------

    """

    def __init__(self, api_key, secret_key, auth_token=None, app_id=None, prefix=None, callback_path=None, internal=None, proxy=None):
        """
        Initializes a new Manyou object which provides wrappers for the Manyou API.

        For web apps, if you are passed an auth_token from Manyou, pass that in as a named parameter.
        Then call:

        manyou.auth.getSession()

        """
        self.api_key = api_key
        self.secret_key = secret_key
        self.session_key = None
        self.session_key_expires = None
        self.auth_token = auth_token
        self.secret = None
        self.uid = None
        self.sid = None
        self.page_id = None
        self.in_canvas = False
        self.added = False
        self.app_id = app_id
        self.prefix = prefix
        self.callback_path = callback_path
        self.internal = internal
        self._friends = None
        self.proxy = proxy

        for namespace in METHODS:
            self.__dict__[namespace] = eval('%sProxy(self, \'%s\')' % (namespace.title(), 'manyou.%s' % namespace))

        self.auth = AuthProxy(self, 'manyou.auth')

    def unicode_encode(self, str):
        """
        @author: houyr
        Detect if a string is unicode and encode as utf-8 if necessary
        """
        return isinstance(str, unicode) and str.encode('utf-8') or str

    def _hash_args(self, params, args, secret=None):
        """Hashes arguments by joining key=value pairs, appending a secret, and then taking the MD5 hex digest."""
        #@author: houyr
        #Fix for UnicodeEncodeError
        params_str = '&'.join(['%s=%s' % (self.unicode_encode(x), self.unicode_encode(params[x])) for x in sorted(params.keys())])
        args_str = '&'.join(['args[%s]=%s' % (self.unicode_encode(x), self.unicode_encode(args[x])) for x in sorted(args.keys()) if x != 'session_key'])
        if args_str:
            str = params_str + '&' + args_str
        else:
            str = params_str
        if secret:
            str += '&'+secret
        elif self.secret:
            str += '&'+self.secret
        else:
            str += '&'+self.secret_key
        hasher = md5.new(str)
        return hasher.hexdigest()


    def _parse_response_item(self, node):
        """Parses an XML response node from Manyou."""
        # temp fix for friends_getAppUsers_response
        if node.nodeName == 'friends_getAppUsers_response':
            return self._parse_response_list(node)
        
        if node.nodeType == node.DOCUMENT_NODE and \
            node.childNodes[0].hasAttributes() and \
            node.childNodes[0].hasAttribute('list') and \
            node.childNodes[0].getAttribute('list') == "true":
            return {node.childNodes[0].nodeName: self._parse_response_list(node.childNodes[0])}
        elif node.nodeType == node.ELEMENT_NODE and \
            node.hasAttributes() and \
            node.hasAttribute('list') and \
            node.getAttribute('list')=="true":
            return self._parse_response_list(node)
        elif len(filter(lambda x: x.nodeType == x.ELEMENT_NODE, node.childNodes)) > 0:
            return self._parse_response_dict(node)
        else:
            return ''.join(node.data for node in node.childNodes if node.nodeType in [node.TEXT_NODE, node.CDATA_SECTION_NODE])


    def _parse_response_dict(self, node):
        """Parses an XML dictionary response node from Manyou."""
        result = {}
        for item in filter(lambda x: x.nodeType == x.ELEMENT_NODE, node.childNodes):
            result[item.nodeName] = self._parse_response_item(item)
        if node.nodeType == node.ELEMENT_NODE and node.hasAttributes():
            if node.hasAttribute('id'):
                result['id'] = node.getAttribute('id')
        return result


    def _parse_response_list(self, node):
        """Parses an XML list response node from Manyou."""
        result = []
        for item in filter(lambda x: x.nodeType == x.ELEMENT_NODE, node.childNodes):
            result.append(self._parse_response_item(item))
        return result


    def _check_error(self, response):
        """Checks if the given Manyou response is an error, and then raises the appropriate exception."""
        if type(response) is dict and response.has_key('error_code'):
            raise ManyouError(response['error_code'], response['error_msg'], response.get('request_args','no request_args found'))


    def _build_post_args(self, method, args=None):
        """Adds to args parameters that are necessary for every call to the API."""
        if args is None:
            args = {}
        
        for arg in args.items():
            if type(arg[1]) == list:
                args[arg[0]] = ','.join(str(a) for a in arg[1])
            elif type(arg[1]) == unicode:
                args[arg[0]] = arg[1].encode("UTF-8")
            
        params = {}
        params['method'] = '.'.join(method.split('.')[1:])
        params['api_key'] = self.api_key
        params['v'] = '1.0'
        params['format'] = RESPONSE_FORMAT
        params['session_key'] = self.session_key
        
        args['sig'] = self._hash_args(params, args)
        #This sucks! Manyou requires you to wrap all api args in args[key]
        for k,v in args.items():
            if k != 'sig' and k != 'session_key':
                args['args[%s]' % k] = v
                del args[k]
        args['method'] = params['method']
        args['api_key'] = params['api_key']
        args['v'] = params['v']
        args['format'] = RESPONSE_FORMAT
        
        return args

    def _add_session_args(self, args=None):
        """Adds 'session_key' and 'call_id' to args, which are used for API calls that need sessions."""
        if args is None:
            args = {}

        if not self.session_key:
            return args

        args['session_key'] = self.session_key
#        args['call_id'] = str(int(time.time() * 1000))

        return args

    def _parse_response(self, response, method, format=None):
        """Parses the response according to the given (optional) format, which should be either 'JSON' or 'XML'."""
        if not format:
            format = RESPONSE_FORMAT

        if format == 'JSON':
            result = simplejson.loads(response)
            self._check_error(result)
        elif format == 'PHP':
            dom = minidom.parseString(response)
            result = self._parse_response_item(dom)
            dom.unlink()

            if 'error_response' in result:
                self._check_error(result['error_response'])
            #TODO: need to find out more about manyou error msg
            result = result[method[8:].replace('.', '_') + '_response']
        else:
            raise RuntimeError('Invalid format specified.')

        return result

    def unicode_urlencode(self,params):
        """
        @author: houyr
        A unicode aware version of urllib.urlencode
        """
        if isinstance(params, dict):
            params = params.items()
        return urllib.urlencode([(k, self.unicode_encode(v))
                          for k, v in params])

    def __call__(self, method, args=None, secure=False):
        """Make a call to Manyou's REST server."""
        post_data = self.unicode_urlencode(self._build_post_args(method, args))
        if self.proxy:
            proxy_handler = urllib2.ProxyHandler(self.proxy)
            opener = urllib2.build_opener(proxy_handler)
            if secure:
                response = opener.open(MANYOU_SECURE_URL, post_data).read() 
            else:
                response = opener.open(MANYOU_URL, post_data).read()
        else:
            if secure:
                response = urlread(MANYOU_SECURE_URL, post_data)
            else:
                response = urlread(MANYOU_URL, post_data)
        
        return self._parse_response(response, method)

    
    # URL helpers
    def get_app_url(self, prefix=None, suffix=None):
        """
        Returns the URL for this app's canvas page, according to app_id.
        
        """
        prefix = prefix if prefix else self.prefix
        if suffix:
            return urljoin(prefix, 'userapp.php?id=%s&my_suffix=%s' % (self.app_id, base64.urlsafe_b64encode(suffix)))
        else:
            return urljoin(prefix, 'userapp.php?id=%s' % self.app_id)
        
    def get_add_url(self, prefix=None):
        """
        Returns the URL that the user should be redirected to in order to add the application.

        """
        if prefix:
            return urljoin(prefix, 'cp.php?ac=userapp&my_suffix=%2Fuserapp%2Fprivacy%3FappId%3D'+self.app_id)
        else:
            return urljoin(self.prefix, 'cp.php?ac=userapp&my_suffix=%2Fuserapp%2Fprivacy%3FappId%3D'+self.app_id)
        
    def get_avatar_url(self, uid, size="thumb"):
        return "http://uchome.manyou.com/avatar/%s?%s" % (uid,size)

    def login(self, popup=False):
        """Open a web browser telling the user to login to Manyou."""
        import webbrowser
        webbrowser.open(self.get_login_url(popup=popup))


    def check_session(self, request):
        """
        Checks the given Django HttpRequest for Manyou parameters such as
        POST variables or an auth token. If the session is valid, returns True
        and this object can now be used to access the Manyou API. Otherwise,
        it returns False, and the application should take the appropriate action
        (either log the user in or have him add the application).

        """
        self.in_canvas = (request.POST.get('my_sig_in_canvas') == '1')

        if self.session_key and (self.uid or self.page_id):
            return True

        if request.method == 'POST':
            params = self.validate_signature(request.POST)
        else:
            if 'installed' in request.GET:
                self.added = True

            params = self.validate_signature(request.GET)

        if not params:
            return False

        if params.get('in_canvas') == '1':
            self.in_canvas = True

        if params.get('added') == '1':
            self.added = True

        if params.get('expires'):
            self.session_key_expires = int(params['expires'])

        if 'friends' in params:
            if params['friends']:
                self._friends = params['friends'].split(',')
            else:
                self._friends = []
        
        if 'prefix' in params:
            self.prefix = params['prefix']
            
        if 'appId' in params:
            self.app_id = params['appId']

        if 'sessionId' in params:
            self.session_key = params['sessionId']
            if 'sId' in params:
                self.sid = params['sId']
            else:
                return False
            if 'uId' in params:
                self.uid = params['uId']
            else:
                return False
        else:
            return False

        return True


    def validate_signature(self, post, prefix='my_sig', timeout=None):
        """
        Validate parameters passed to an internal Manyou app from Manyou.

        """
        args = post.copy()
        return dict([(key[len(prefix + '_'):], value) for key, value in args.items() if key.startswith(prefix)])
